import { baseRes } from "@@/interfaces/api.interface"
import Taro from "@tarojs/taro"

interface RequestOption<D> extends Taro.request.Option {
  url: string
  params?: D
}
Taro.addInterceptor(e => {
  // console.log(e)
  let requestParams = { ...e.requestParams, header: { token: Taro.getStorageSync("token") || "" } }
  return e
    .proceed(requestParams)
    .then((res: baseRes) => {
      //请求成功
      return res
    })
    .catch((res: Response) => {
      //请求失败
      throw res
    })
})
// function creatRequest<T = {}, D = {}>(config: Taro.request.Option<T>) {
// 	return Taro.request<D, T>({ ...config, mode: "cors", credentials: "include", timeout: 2000, retryTimes: 0 })
// }
function creatRequest<T = {}, D = {}>(config: Taro.request.Option<T>) {
  return Taro.request<D, T>({ ...config, timeout: 2000, retryTimes: 0 })
}

export async function get<R, P = {}>(
  option: RequestOption<P> = {
    url: ""
  }
) {
  try {
    let { url, params, ...config } = option
    let ajax = await creatRequest<P, R>({
      url,
      method: "GET",
      data: params,
      ...config
    })
    return ajax.data
  } catch (res) {
    console.log(res)
    throw res
  }
}
// export async function post<R, P = {}>(
//   option: RequestOption<P> = {
//     url: ""
//   }
// ) {
//   try {
//     let { url, params, ...config } = option
//     let ajax = await creatRequest<P, R>({
//       url,
//       method: "POST",
//       data: params,
//       header: {
//         "content-type": "application/x-www-form-urlencoded"
//       },
//       ...config
//     })
//     return ajax.data
//   } catch (res) {
//     throw res
//   }
// }
export async function postJson<R, P = {}>(
  option: RequestOption<P> = {
    url: ""
  }
) {
  try {
    let { url, params, ...config } = option
    let ajax = await creatRequest<P, R>({
      url,
      method: "POST",
      data: params,
      header: {
        "content-type": "application/json"
      },
      ...config
    })
    return ajax.data
  } catch (res) {
    console.log(res)
    throw res
  }
}
